Expand description
Struson is an RFC 8259 compliant streaming JSON reader and writer.
Its main purpose is allowing to read and write JSON data in a memory efficient way without having to store the complete JSON document structure in memory. It is however not an object mapper which converts structs to JSON and vice versa, a dedicated library such as Serde should be used for that.
The API of Struson was inspired by the streaming API of the Java library Gson. It is rather low-level and corresponds to the elements of a JSON document, with little abstraction on top of it, allowing to read and write any valid JSON document regardless of its structure or content.
Terminology
This crate uses the same terminology as the JSON specification:
- object:
{ ... }
- member: Entry in an object. For example the JSON object
{"a": 1}
has the member"a": 1
where"a"
is the member name and1
is the member value.
- member: Entry in an object. For example the JSON object
- array:
[ ... ]
- literal:
- boolean:
true
orfalse
null
- boolean:
- number: number value, for example
123.4e+10
- string: string value, for example
"text in \"quotes\""
Usage examples
Reading
// In this example JSON data comes from a string;
// normally it would come from a file or a network connection
let json = r#"{"a": [1, true]}"#;
let mut json_reader = JsonStreamReader::new(json.as_bytes());
json_reader.begin_object()?;
assert_eq!("a", json_reader.next_name()?);
json_reader.begin_array()?;
assert_eq!(1_u32, json_reader.next_number()??);
assert_eq!(true, json_reader.next_bool()?);
json_reader.end_array()?;
json_reader.end_object()?;
// Ensures that there is no trailing data
json_reader.consume_trailing_whitespace()?;
Writing
// In this example JSON bytes are stored in a Vec;
// normally they would be written to a file or network connection
let mut writer = Vec::<u8>::new();
let mut json_writer = JsonStreamWriter::new(&mut writer);
json_writer.begin_object()?;
json_writer.name("a")?;
json_writer.begin_array()?;
json_writer.number_value(1)?;
json_writer.bool_value(true)?;
json_writer.end_array()?;
json_writer.end_object()?;
// Ensures that the JSON document is complete and flushes the buffer
json_writer.finish_document()?;
assert_eq!(r#"{"a":[1,true]}"#, String::from_utf8(writer)?);
Serde integration
Optional integration with Serde exists to
allow writing a Serialize
to a JsonWriter
and reading a Deserialize
from
a JsonReader
. See the serde
module of this crate for more information.
Modules
Macros
- Creates a JSONPath from path pieces